﻿package com.sp.pay.common;

import com.sp.pay.dto.sms.SmsDto;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


public class RestClient {

    private final static Log logger = LogFactory.getLog(RestClient.class);

    public static String  post(String url, HttpServletRequest request){
         String result="";
         HttpClient client = new HttpClient();
         client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
         PostMethod httpPost = new PostMethod(url);
         httpPost.setRequestBody(getNameValuePairs(request));
         try{
             client.executeMethod(httpPost);
             result= httpPost.getResponseBodyAsString();
             logger.info("发送返回结果:" + result);
         }catch (Exception e){
             logger.error("post 出错 原因: " + e);
         }
	     return result;
	 }
    static  NameValuePair[] getNameValuePairs(HttpServletRequest request) {

        Enumeration enumeration =(Enumeration)request.getParameterNames();
        List<NameValuePair> list = new  ArrayList<NameValuePair>();
        while(enumeration.hasMoreElements()){
            String parName=(String)enumeration.nextElement();
            list.add(new NameValuePair(parName,request.getParameter(parName)));
        }
        NameValuePair nameValuePair[] = new NameValuePair[list.size()];
        for(int i=0;i<list.size();i++){
            nameValuePair[i]=list.get(i);
        }
       return nameValuePair;
   }

	public static void main(String[] args) {
		
		try {
			String str="http://www.baidu.com";
			
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			//http://61.152.107.59:9000/smsin?cpnumber=10330&encodeStr=12KVUlAKv8K0DRaQLNjKmBwO2VpvWIzMeeJYdPJjBJPSCbQIHz4yvw%3D%3D
			//String url="http://61.152.107.59:9000/smsin?cpnumber=" +CPID+ "&encodestr=" +encodeStr;
			GetMethod httppost = new GetMethod(str);
			//PostMethod httppost = new PostMethod(str);
//			httppost.setRequestBody(new NameValuePair[] {
//					
//					new NameValuePair("keywords", "04620289177|V1.0|DR10|2|12|21|")});
			
			System.out.println(httppost.getResponseBodyAsString()); //aa为0时表示发送成功
			client.executeMethod(httppost);
			if (httppost.getStatusCode() == HttpStatus.SC_OK) {
				System.out.println("send sms succeed.result="
						+ httppost.getResponseBodyAsString());
				System.out.println(httppost.getResponseBodyAsString());
			} else {
				System.out.println("send sms Unexpected failure: "
						+ httppost.getStatusLine().toString());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

